<template>
<div class="container">
  <el-form ref="form" :model="form" label-width="80px" @submit.prevent="onSubmit" style="margin:20px;width:60%;min-width:600px;">
    <el-form-item label="部门名称">
      <el-input v-model="form.name"></el-input>
    </el-form-item>

    <el-form-item label="部门简介">
      <el-input v-model="form.intro"></el-input>
    </el-form-item>
    <el-form-item label="部门主管">
      <el-autocomplete
          v-model="form.managerId"
          :fetch-suggestions="findEmploy"
          placeholder="请输入内容"
          @select="selectEmploye"
      ></el-autocomplete>
    </el-form-item>

    <el-form-item label="上级部门">
      <el-cascader
          v-model="form.parentId"
          :options="parentDept"></el-cascader>
      <el-form-item>
    </el-form-item>

      <el-button type="primary" @click="add">立即创建</el-button>
      <el-button @click.native.prevent @click="cancleAdd">取消</el-button>
    </el-form-item>
  </el-form>
</div>
</template>

<script>
import axios from "axios";

export default {
  name: "addDept",
  data(){
    return{
      employId:'',
      parentDept:[],
      form:{
        name:'',
        intro:'',
        managerName:'',
        managerId:'',
        parentId:'',
        path:'',
      }
    }
  },
  methods:{
    //取消添加
    cancleAdd(){
      this.$bus.$emit('closeAddDept',false);
    },
    //添加员工
    add(){
      //处理数据
      let parentIds = this.form.parentId;

      let paths ='';
      for (let i = 0; i < parentIds.length; i++) {
        paths+='/'+parentIds[i];
      }

      paths.split(paths.length-1,1);
      this.form.path=paths;
      this.form.parentId=this.form.parentId[this.form.parentId.length-1]+'';
      console.info('处理的数据',this.form)
      axios({
        url:'http://localhost:8080/api/tOrgDepartment/add',
        type:'post',
        method:'post',
        data:this.form
      }).then(resp=>{
        if (resp.data.code!=200){
          this.$message({
            message:resp.data.msg,
            type:'error'
          })
          //关闭添加部门对话框
          this.$bus.$emit('closeAddDept',false);
        }
        else {
          this.$message({
            message:resp.data.msg,
            type:'success'
          })
          //关闭添加部门对话框
          this.$bus.$emit("closeAddDept",true);
        }
      })
    },
    findEmploy(query,cb){
      axios.get('http://localhost:8080/api/employ/findByNameLike?keyWorld='+query)
      .then((resp)=>{
        let data = resp.data.data;
        let names = [];
        for (let i = 0; i < data.length; i++) {

          let obj={
            value:data[i].username,
            id:data[i].id
          }
          names.push(obj)
        }
        cb(names)
      })
    },
    selectEmploye(item){
      this.form.managerId=item.id
    }
  },
  mounted() {
    this.$bus.$on('addDept',(deptList)=>{
      this.parentDept=deptList
      //查询所有员工信息
    })
  }
}
</script>

<style scoped>

</style>